/**
 * Created by ahwwl on 17-7-28.
 */
(function($){

    $.fn.datatables=function(p)
    {
        p = $.extend({
            columns:[],
            mobile_field:[],
            ajax:{},
            data:[],
            emptyMsg:"empty",
            page:1,
            page_total:1,
            rows:15,
            rows_list:[15,30,50,100],
            total:0
        },p);
        p.ajax = $.extend({url:"",type:"get",success:null,dataType:"json",parems:{}},p.ajax);
        var is_mobile = false;
        var table = $('<table class="table table-hover"></table>').appendTo($(this));
        var thead = $('<thead></thead>').appendTo(table);
        var tbody = $('<tbody></tbody>').appendTo(table);
        var theadtr = $('<tr></tr>').appendTo(thead);
        var tfooter = $('<div></div>').appendTo($(this));
        var th = "";
        var field = "";
        var td = "";
        var tbodytr = "";
        var _this = this;
        var selectdiv = null;
        var footer_show = "";


        var g = {
            init:function(){
                selectdiv =$('<div class="pageselect" style="float:left;width:70px;"></div>').appendTo(tfooter);
                var selectrows = $('<select name="rows" class="rows_select" lay-ignore style="height: 37px;width:50px;"></select>').appendTo(selectdiv);
                if(g.settings.rows_list.length>0)
                {
                    for(var i =0;i<g.settings.rows_list.length;i++)
                    {
                        $('<option value="'+p.rows_list[i]+'">'+p.rows_list[i]+'</option>').appendTo(selectrows);
                    }
                }
                if(g.settings.rows > 0)
                {
                    selectrows.val(g.settings.rows);
                }

                $('<div class="pageinfo" style="margin-left:10px;float:left;" id="'+g.page_id+'"></div>').appendTo(tfooter);
                footer_show = $('<div class="dataTables_info" style="margin-left:10px;float:left;height:37px;line-height: 35px;"></div>').appendTo(tfooter);
                tfooter.append("<div style='clear:both;height:1px;'>&nbsp;</div>")
                selectrows.change(function () {
                    g.settings.rows = $(this).val();
                    g.ajax();
                });
                g.ajax();

            },
            ajax:function () {

                if(g.settings.ajax.url.length>0)
                {
                    // var index = layer.load(2, {shade: 0.4});
                    var callback = g.settings.ajax.callback;
                    g.settings.ajax.success = function (msg) {
                        g.settings.data = [];
                        if(msg.error === 0)
                        {
                            if(msg.data)
                            {
                                g.settings.data = msg.data;
                            }
                            if(msg.total)
                            {
                                g.settings.total = msg.total
                            }
                            if(msg.page)
                            {
                                g.settings.page = msg.page
                            }
                            if(msg.rows)
                            {
                                g.settings.rows = msg.rows
                            }
                            g.settings.page_total = Math.ceil(g.settings.total/g.settings.rows);
                        }
                        g.load();
                        if(callback)
                        {
                            callback(msg);
                        }

                    };
                    g.settings.ajax.error = function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest, textStatus, errorThrown);
                        // layer.close(index);
                        openMsg("http status error:"+errorThrown);
                    };
                    g.settings.ajax.data = $.extend({page:g.settings.page,rows:g.settings.rows},g.settings.ajax.data);
                    g.settings.ajax.data.page = g.settings.page;
                    g.settings.ajax.data.rows = g.settings.rows;
                    var ajax_info = $.extend({},g.settings.ajax);
                    if(g.settings.ajax.parems)
                    {
                        ajax_info.data = $.extend(g.settings.ajax.parems,ajax_info.data);
                    }
                    $.ajax(ajax_info);

                }else{
                    g.load();
                }
            },

            getColumns:function () {
                var columns = g.settings.columns;
                if(is_mobile)
                {
                    if(g.settings.mobile_field.length>0)
                    {
                        columns = [];

                        for(var ii=0;ii<g.settings.columns.length;ii++)
                        {
                            field = g.settings.columns[ii].field;
                            if(g.inArray(field,g.settings.mobile_field))
                            {
                                columns.push(g.settings.columns[ii]);
                            }
                        }
                    }else{
                        columns = columns.slice(0,3);
                    }

                }
                return columns;
            },
            getOtherColumns:function (obj) {
                tbodytr = $('<tr class="open"></tr>').insertAfter(obj);
                var row = obj[0].row;
                var mobile_field = [];
                var tdobj = $("td",obj);
                for(var i=0;i<tdobj.length;i++)
                {
                    mobile_field.push(tdobj.eq(i).attr("field"));
                }

                td = $("<td colspan='"+mobile_field.length+"'></td>").appendTo(tbodytr);
                var ul = $("<ul></ul>").appendTo(td);
                for(var ii=0;ii<g.settings.columns.length;ii++)
                {
                    field = g.settings.columns[ii].field;
                    var title = g.settings.columns[ii].title;

                    if(!g.inArray(field,mobile_field))
                    {

                        var li =$("<li></li>").appendTo(ul);
                        li.append('<span class="dtr-title" style="width:100px;display:inline-block;">'+title+':</span>');

                        if(field)
                        {
                            li.attr("field",field);
                        }
                        // if(g.settings.columns[ii].hidden)
                        // {
                        //     li.addClass("hide");
                        // }
                        if(g.settings.columns[ii].formatter)
                        {
                            var h = g.settings.columns[ii].formatter(row[field], row, i);
                            var span = $('<span class="dtr-title"></span>');
                            span.append(h);
                            li.append(span);
                        }else{
                            li.append('<span class="dtr-title">'+row[field]+'</span>');
                        }
                    }
                }
                if(is_mobile)
                {
                    $(".dropdown-menu",table).removeClass("pull-right");
                }
            },
            inArray:function (k,array)
            {
                for(var i=0;i<array.length;i++)
                {
                    if(array[i] == k)
                    {
                        return true;
                    }
                }
                return false;
            },
            head:function () {
                theadtr.html("");
                var columns = g.getColumns();

                for(var i =0;i<columns.length;i++)
                {
                    th = $("<th ></th>").appendTo(theadtr);
                    if(columns[i])
                    {
                        var field = columns[i].field;
                        if(field)
                        {
                            th.attr("field",field);
                        }
                        if(columns[i].checkbox)
                        {
                            var text = '<div class="table_div  " style="width:50px;display:block;"> ' +
                                '<input id="'+g.checkbox_id+'"  type="checkbox"  name="all_ck">' +
                                '<div class="btn-group field_list_checked" tabindex="-1"> ' +
                                '<a class="dropdown-toggle" > ' +
                                '<i class="fa fa-bars"></i> ' +
                                '</a> ' +
                                '<ul role="menu" class="dropdown-menu pull-left">';
                            text += '</ul> ' +
                                '</div>'+
                                '</div>';

                            th.html(text);
                        }else if(columns[i].title)
                        {
                            th.html('<div class="table_div">'+columns[i].title+'</div>');
                        }
                        if(columns[i].hidden)
                        {
                            th.addClass("hide");
                        }
                        if(columns[i].width)
                        {
                            $(".table_div",th).width(columns[i].width);
                        }
                    }


                }
            },
            body:function () {


                tbody.html("");
                var row = {};
                var idFieldValue="";
                var columns = g.getColumns();
                if(g.settings.data.length>0)
                {

                    for(var i=0;i<g.settings.data.length;i++)
                    {
                        row = g.settings.data[i];
                        tbodytr = $('<tr></tr>').appendTo(tbody);
                        tbodytr[0].row = row;
                        for(var f=0;f<columns.length;f++)
                        {

                            if(columns[f])
                            {
                                td = $("<td ></td>").appendTo(tbodytr);
                                var openicon = "";
                                if(f == 0&&is_mobile)
                                {
                                    openicon = '<a href="javascript:void 0;" class="openicon glyphicon glyphicon-plus-sign" style="margin: 0 5px;"></a>';
                                }
                                field = columns[f].field;
                                if(field)
                                {
                                    td.attr("field",field);
                                }
                                if(columns[f].checkbox)
                                {

                                    if(g.settings.idField && row[g.settings.idField])
                                    {
                                        idFieldValue = row[g.settings.idField];
                                    }
                                    td.html(openicon+'<div class="table_div  " style="display: inline-block;"><input name="'+field+'" value="'+idFieldValue+'" id="'+g.checkbox_id+'_'+idFieldValue+'" type="checkbox"></div>');
                                }else if(row[field] ||row[field]==0)
                                {
                                    td.html(openicon+'<div class="table_div" style="display: inline-block;" title="'+row[field]+'">'+row[field]+'</div>');

                                }
                                if(columns[f].hidden)
                                {
                                    td.addClass("layui-hide");
                                }
                                if(columns[f].css)
                                {
                                    td.find(".table_div").css(columns[f].css);
                                }
                                if(columns[f].formatter)
                                {
                                    td.empty();
                                    var h = columns[f].formatter(row[field], row, i);
                                    td.append(openicon);
                                    var table_div = $('<div class="table_div" title=""></div>');
                                    if(h)
                                    {
                                        table_div.append(h);
                                        if(h instanceof jQuery)
                                        {
                                            h[0].row = row;
                                        }
                                    }
                                    td.append(table_div);
                                }
                            }


                        }
                    }
                }else{
                    tbodytr = $('<tr><td colspan="'+g.settings.columns.length+'">'+g.settings.emptyMsg+'</td></tr>').appendTo(tbody);
                }

                $(".openicon",table).click(function () {
                    if($(this).hasClass("glyphicon-plus-sign"))
                    {
                        $(this).removeClass("glyphicon-plus-sign").addClass("glyphicon-minus-sign");
                        if($(this).parents("tr").next().is(".open").length>0)
                        {
                            $(this).parents("tr").next().is(".open").remove();
                        }

                        g.getOtherColumns($(this).parents("tr"));
                    }else{
                        $(this).addClass("glyphicon-plus-sign").removeClass("glyphicon-minus-sign");
                        if($(this).parents("tr").next().is(".open"))
                        {
                            $(this).parents("tr").next().remove();
                        }

                    }
                });


            },
            loadPage:function () {
                var text = '<ul class="pagination nomargin pull-left">';
                text += '<li ><a href="javascript:void 0;" class="page_frist"><i class="fa fa-angle-double-left"></i></a></li>';
                text += '<li ><a href="javascript:void 0;" class="page_priv"><i class="fa fa-angle-left"></i></a></li>';
                text += '<li class="disabled"><a href="javascript:void 0;"><input class="form-control" style="width:30px;height:18px;padding:0;text-align: center;" value="'+g.settings.page+'">/'+g.settings.page_total+'页</a></li>';
                text += '<li ><a href="javascript:void 0;"class="page_next"><i class="fa fa-angle-right"></i></a></li>';
                text += '<li ><a href="javascript:void 0;"class="page_last"><i class="fa fa-angle-double-right"></i></a></li>';
                text += '</ul>';
                $("#"+g.page_id).html(text);
                if(g.settings.page <= 1)
                {
                    $("#"+g.page_id).find(".page_frist").parent().addClass("disabled");
                    $("#"+g.page_id).find(".page_priv").parent().addClass("disabled");
                }else if(g.settings.page >= g.settings.page_total)
                {
                    $("#"+g.page_id).find(".page_next").parent().addClass("disabled");
                    $("#"+g.page_id).find(".page_last").parent().addClass("disabled");
                }
                $("#"+g.page_id+" li:not(.disabled)").click(
                    function () {
                        var page = 1;
                        var obj = $(this).find("a");

                        if(obj.hasClass("page_frist"))
                        {
                            page = 1;
                        }else if(obj.hasClass("page_priv"))
                        {
                            page = parseInt(g.settings.page) - 1;
                        }else if(obj.hasClass("page_next"))
                        {
                            // console.log("page_next")
                            page = parseInt(g.settings.page) +1;
                            // console.log(page)
                        }else if(obj.hasClass("page_last"))
                        {
                            page = parseInt(g.settings.page_total);
                        }else{
                            return false;
                        }
                        g.setPage(page);
                    }
                );
                $("#"+g.page_id+" input").keypress(function (event) {
                    var page = $(this).val();
                    if(event.keyCode==13 && !isNaN(page)){
                        g.setPage(page);
                    }
                });

            },
            footer:function () {

                g.loadPage();
                var start_num=(parseInt(g.settings.page)-1)*parseInt(g.settings.rows)+1;
                var end_num = start_num+parseInt(g.settings.rows)-1;
                if(end_num>parseInt(g.settings.total))
                {
                    end_num = parseInt(g.settings.total);
                }
                if(start_num>parseInt(g.settings.total)) {
                    start_num = parseInt(g.settings.total);
                }
                footer_show.html('显示'+start_num+'到'+end_num+',共'+g.settings.total+'记录');
                selectdiv.removeClass("layui-hide");
                $("#"+g.page_id).removeClass("layui-hide");
                if(g.settings.rows < 2)
                {
                    tfooter.find(".pageselect,.pageinfo").hide();
                }

                $("#"+g.menu_id).click(function () {
                    // if($(this).parent().hasClass("open"))
                    // {
                    //     $(this).parent().removeClass("open");
                    // }else{
                    //     $(this).parent().addClass("open");
                    // }
                    //  alert("aaa");
                });
                $("input[type='checkbox']",_this).formCheckLabel();
                $("select",_this).formSelect();

            },
            setPage:function (page) {
                if(page>g.settings.page_total)
                {
                    page = g.settings.page_total;
                }
                if(page != g.settings.page)
                {
                    g.settings.page = page;
                    g.ajax();
                }

            },
            load:function () {
                if($(window.top).width() <600)
                {

                    is_mobile = true;
                }else{
                    is_mobile = false;
                }
                g.head();
                g.body();
                g.footer();

            },
            setParems:function (data) {
                g.settings.ajax.parems = data;
            },
            getRows:function (obj) {
                var row_list = [];

                var row1 = {};
                if(obj)
                {
                    row1 = obj.parents("tr").row;
                    row_list.push(row1);
                }else{
                    var objs = $("tr>td:eq(0) input[type='checkbox']:checked",table);
                    for(var i =0;i<objs.length;i++)
                    {
                        if(objs.eq(i).parents("tr").length>0)
                        {
                            row1 = objs.eq(i).parents("tr")[0].row;
                            row_list.push(row1);
                        }

                    }
                }

                return row_list;
            }
        };
        g.settings = p;
        var times = (new Date()).valueOf();
        g.page_id = "pager_"+times;
        g.checkbox_id = "checkbox_id_"+times;
        g.menu_id = "menu_id_"+times;
        g.init();
        $(this).each(function () {
            this.grid = g;
        });
        table.delegate("#"+g.checkbox_id,"click",function () {

            var child = table.find('tbody input[type="checkbox"]');
            var checked = $(this)[0].checked;

            // child.eq(0).attr("checked",$(this)[0].checked);
            child.each(function(index, item){
                item.checked = checked;
                $(item).trigger("change");
            });
        });
        table.delegate("td","contextmenu",function (e) {
            if(e.which == 3)
            {
                var menu = $(this).parent().find(".btn-group>ul.dropdown-menu");
                if(menu.length>0)
                {
                    menu = menu.clone(true,true)
                }else{
                    return false;
                }
                var popup = menu;
                var left = e.pageX + 5, /* nudge to the right, so the pointer is covering the title */
                    top = e.pageY;
                if (top + popup.height() >= $(window).height()) {
                    top -= popup.height();
                }
                if (left + popup.width() >= $(window).width()) {
                    left -= popup.width();
                }
                popup[0].row = $(this).parent()[0].row;
                popup.removeClass("pull-right");
                popup.css({zIndex:1000001, left:left, top:top});
                popup.appendTo($("body"));
                popup.attr("tabindex","-1");
                popup.show();
                popup.focus();
                popup.focusout(function (e) {
                    if(e.relatedTarget)
                    {
                        if ($(e.relatedTarget).parents(".dropdown-menu")[0] == $(this)[0]){
                            return false;
                        }
                    }
                    $(this).remove();
                });



                // table.find(".btn-group").removeClass("open");
                // $(this).parents("tr").find(".btn-group").addClass("open");
            }
            return false;
        });
        table.delegate(".field_list_checked .dropdown-toggle","click",function(){
            var ul = $(this).next("ul");
            ul.empty();
            var mobile_field = g.settings.mobile_field;
            if(g.settings.columns.length>0)
            {
                for(var i=0;i<g.settings.columns.length;i++)
                {
                    var field = g.settings.columns[i];
                    if(field.title)
                    {
                        var li = $('<li></li>');
                        var input = $('<input  name="field_list" value="" type="checkbox">');
                        var is_checked = field.hidden?0:1;

                        if(is_mobile)
                        {
                            if($.inArray(field.field,mobile_field)!=-1)
                            {
                                is_checked = true;
                            }else{
                                is_checked = false;
                            }
                        }
                        input.attr({value:field.field,title:field.title});
                        input[0].checked = is_checked;
                        input.appendTo(li);
                        li.appendTo(ul);
                    }
                }
            }

            ul.find("input").formCheckLabel();
            $(this).parent().addClass("open");
        });
        table.delegate(".field_list_checked","focusout",function(){
            var ul = table.find(".field_list_checked>ul");
            g.settings.mobile_field = ["ck"];
            ul.find("li input:checked").each(function () {
                g.settings.mobile_field.push($(this).val());
            });
            if(g.settings.columns.length>0)
            {
                for(var i=0;i<g.settings.columns.length;i++)
                {
                    var field = g.settings.columns[i];
                    if(field.title)
                    {
                        if($.inArray(field.field,g.settings.mobile_field)!=-1)
                        {
                            g.settings.columns[i].hidden = false;
                        }else{
                            g.settings.columns[i].hidden = true;
                        }
                    }
                }
            }
            $(this).removeClass("open");
            g.load();
        });

        // console.log(this.grid)
        return g

    };
    $.fn.setParems = function (data) {
        return this.each(function () {
            this.grid.setParems(data);
        });
    };
    $.fn.reload = function () {
        return this.each(function () {
            this.grid.setPage(1);
            this.grid.ajax();

        });
    };
    $.fn.load = function () {
        return this.each(function () {
            this.grid.load();
        });
    };
    $.fn.getRows = function (obj,fields) {
        var row_list = [];

        var row1 = {};

        if(obj)
        {
            if($(obj).parents("tr").length>0)
            {
                row1 = $(obj).parents("tr")[0].row;
            }else if($(obj).parents("ul")&&$(obj).parents("ul")[0].row)
            {
                row1 = $(obj).parents("ul")[0].row;
            }
            if(!$.isEmptyObject(row1))
            {
                row_list.push(row1);
            }
        }else{
            var objs = $("tr td input[type='checkbox']:checked",this);
            for(var i =0;i<objs.length;i++)
            {
                if(objs.eq(i).parents("tr").length>0)
                {
                    row1 = objs.eq(i).parents("tr")[0].row;
                    var row2 = {};
                    if(fields)
                    {
                        for(var f=0;f<fields.length;f++)
                        {
                            row2[fields[f]]=row1[fields[f]];
                        }
                    }else{
                        row2 = row1;
                    }
                    row_list.push(row2);
                }

            }
        }

        return row_list;


    };
})(jQuery);